var accessid = '',
    accesskey = '',
    host = '',
    policyBase64 = '',
    signature = '',
    callbackbody = '',
    filename = '',
    key = '',
    expire = 0,
    g_object_name = '',
    g_object_name_type = '',
    now = timestamp = Date.parse(new Date()) / 1000;

function send_request() {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlhttp!=null) {
        serverUrl = "/aliyunoss/uptoken?type=article";
        // serverUrl = "<?= URL::site('aliyunoss/uptoken?type=article')?>";
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText
    } else {
        alert("Your browser does not support XMLHTTP.");
    }
}

function check_object_radio() {
    var tt = document.getElementsByName('myradio');
    for (var i = 0; i < tt.length ; i++ ) {
        if(tt[i].checked) {
            g_object_name_type = tt[i].value;
            break;
        }
    }
}

function get_signature() {
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse(new Date()) / 1000;
    if (expire < now + 3) {
        body = send_request()
        var obj = eval ("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback']
        key = obj['dir']
        return true;
    }
    return false;
}

function random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename) {

    suffix = get_suffix(filename)
    g_object_name = key + random_string(10) + suffix
    return ''
}

function get_uploaded_object_name() {
    return g_object_name
}

function set_upload_param(up, filename, ret) {
    if (ret == false) {
        ret = get_signature();
    }
    g_object_name = key;
    if (filename != '') {
        suffix = get_suffix(filename);
        calculate_object_name(filename);
    }
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'callback' : callbackbody,
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

/**
 *
 * @param dn    上传按钮id
 * @param dn1   接受容器id
 * @param type  上传文件类型   img 上传图片   video 上传视频
 * @param multi_selection  批量上传选项
 */
var init_upload = function(dn,dn1,type,multi_selection=false) {
    var extensions = '';
    if(type === 'img'){
        extensions = 'jpg,gif,png';
    }else if(type === 'video'){
        extensions = 'mpg,m4v,mp4,flv,3gp,mov,avi,rmvb,mkv,wmv';
    }
    var uploader = new plupload.Uploader({
        browse_button: dn,
        multi_selection: multi_selection,   //true开启批量上传
        url: 'http://oss.aliyuncs.com',
        flash_swf_url: "<?= URL::site('static/js/plupload/Moxie.swf')?>",
        silverlight_xap_url: "<?= URL::site('static/js/plupload/Moxie.xap')?>",
        filters: {
            mime_types: [
                {title: " file type ", extensions: extensions}
                ],
            max_file_size: '102400kb',                  //最大只能上传102400kb的文件
            // prevent_duplicates: true                //不允许选取重复文件
        },
        init: {
            FilesAdded: function(up, files) { //文件上传前
                plupload.each(files, function (file,index) {
                    var progress = new FileProgress(file, dn1 ,type);
                    $('#'+dn).hide();
                    $('input[type=file]').parent('div').hide();
                    // var remove_btn = $('#' + file.id).find('.close');
                    var remove_btn = $('#' + dn1 + ' .up-item').eq(index).find('.close');
                    remove_btn.click(function () {
                        $('#' + file.id).remove();
                        $('#'+dn).show();
                    });
                });
                set_upload_param(uploader, '', false);
            },
            BeforeUpload:function (up, file) {
                $('#' + file.id).find('.progress').show();
                set_upload_param(up, file.name, true);
                this.start();
            },
            UploadProgress:function (up, file) {
                var progress = new FileProgress(file, dn1, type);
                progress.setProgress(file.percent);
            },
            FileUploaded:function (up,file,info) {
                var progress = new FileProgress(file, dn1, type);
                progress.setComplete(up, file, info);
                // console.log(info);
                if (info.status == 200) {
                    var url = 'http://jtkj.oss-cn-beijing.aliyuncs.com/' + get_uploaded_object_name();
                    if(type == 'img'){
//                         url = url + '?x-oss-process=image/resize,m_fill,h_120,w_160';
                    }
                    $('#' + file.id).find('video').attr('src', url);
                    $('#' + file.id).find('input').val(url);
                }
            },
            Error:function (up, err) {
                alert(err.message);
            }
        }
    });
    uploader.init();
};

function pic_close(obj,dn) {
    $(obj).parent().remove();
    $('#'+dn).show();
}



